﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.Mod.Groups.Events
{
    using SharingCenter.Web.Classes;
    using SharingCenter.Web.Classes.Requests;
    using SharingCenter.Web.Classes.Events;
    using SharingCenter.Web.Classes.Profiles;
    using SharingCenter.Web.Classes.Message;
    public partial class Event : GroupsPageBase
    {
        string q;
        protected Sc_Profile myProfile;
        Dictionary<string, string> mailReplacement;

        protected void Page_Init(object sender, EventArgs e)
        {
            ParseGroupIdFromQueryString();
            HasRights(groupId, Profile.UserId, true);
            SiteMap.SiteMapResolve += new SiteMapResolveEventHandler(this.SiteMap_SiteMapResolve);
        }

        protected void Page_Unload(object sender, EventArgs e)
        {
            SiteMap.SiteMapResolve -= new SiteMapResolveEventHandler(this.SiteMap_SiteMapResolve);
        }

        private SiteMapNode SiteMap_SiteMapResolve(object sender, SiteMapResolveEventArgs e)
        {
            SiteMapNode currentNode = SiteMap.CurrentNode.Clone(true);
            SiteMapNode tmpNode = currentNode;
            if (null != (tmpNode = tmpNode.ParentNode))
            {
                tmpNode.Url += "?id=" + groupId;
            }

            if (null != (tmpNode = tmpNode.ParentNode))
            {
                tmpNode.Title = group.GroupName;
                tmpNode.Url += "?id=" + groupId;
            }
            return currentNode;
        }

        void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
        {
            LinqDataSource1.Select = null;

            // Make start date/time
            TextBox startDate = (TextBox)FormView1.FindControl("txtStartDate");
            NumericDropDownList hrs = (NumericDropDownList)FormView1.FindControl("nddStartHours");
            NumericDropDownList mins = (NumericDropDownList)FormView1.FindControl("nddStartMins");
            DateTime start = Convert.ToDateTime(string.Format("{0} {1}:{2}", startDate.Text, hrs.SelectedValue, mins.SelectedValue));
            //start.Add(new TimeSpan(int.Parse(hrs.SelectedValue), int.Parse(mins.SelectedValue), 0));

            TextBox endDate = (TextBox)FormView1.FindControl("txtEndDate");
            hrs = (NumericDropDownList)FormView1.FindControl("nddEndHours");
            mins = (NumericDropDownList)FormView1.FindControl("nddEndMins");
            DateTime end = Convert.ToDateTime(string.Format("{0} {1}:{2}", endDate.Text, hrs.SelectedValue, mins.SelectedValue));

            TextBox closeSignDate = (TextBox)FormView1.FindControl("txtSignUpCloseDate");
            hrs = (NumericDropDownList)FormView1.FindControl("nddSignUpCloseHours");
            DateTime closeSignUp = Convert.ToDateTime(string.Format("{0} {1}:00", closeSignDate.Text, hrs.SelectedValue, mins.SelectedValue));

            e.Values["StartDate"] = start;
            e.Values["EndDate"] = end;
            e.Values["SignUpCloseDate"] = closeSignUp;
            e.Values["CreationDate"] = DateTime.Now;
            e.Values["EventId"] = System.Guid.NewGuid();
            e.Values["AdminApproved"] = true;

            mailReplacement = new Dictionary<string, string>();
            mailReplacement.Add("Title", e.Values["Title"].ToString());
            mailReplacement.Add("StartDate", start.ToString());
            mailReplacement.Add("EndDate", end.ToString());
            mailReplacement.Add("SignUpDeadline", closeSignUp.ToString());
            mailReplacement.Add("EventLink", string.Format("{0}/Mod/Events/View.aspx?id={1}", WebConsts.SITE_URL, e.Values["EventId"].ToString()));

            //CheckBox ch = (CheckBox)FormView1.FindControl("chkCreatorSignUp");
            //if (ch.Checked)
            //{
            //    string genderKey = myProfile.Gender == SharingCenter.Web.Classes.enums.Gender.Female ? "FemaleParticipants" : "MaleParticipants";
            //    e.Values[genderKey] = 1;
            //}
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            FormView1.ItemInserting += new FormViewInsertEventHandler(FormView1_ItemInserting);
            FormView1.ItemInserted += new FormViewInsertedEventHandler(FormView1_ItemInserted);

            q = Request.QueryString["q"];

            if (q == null)
            {
                q = "new";
            }

            if (!IsPostBack)
            {
                InitializeFormData();
            }

            myProfile = ProfileOperations.GetProfile(Profile.UserId);
        }

        void LinqDataSource1_Inserted(object sender, LinqDataSourceStatusEventArgs e)
        {
            if (e.Exception != null)
            {
                RaiseError(e.Exception, WebConsts.ERROR_MESSAGE_DEFAULT);
            }
        }

        void LinqDataSource1_Inserting(object sender, LinqDataSourceInsertEventArgs e)
        {
            if (e.Exception != null)
            {
                RaiseError(e.Exception, WebConsts.ERROR_MESSAGE_DEFAULT);
            }
            else
            {
                e.Cancel = true;
            }
        }

        void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e)
        {
            if (e.Exception == null)
            {
                CreatorSignUp((Guid)e.Values["EventId"]);
                SendMail();
                SetTopMostMessage("已成功发布一条活动信息。", true);
                Response.Redirect("Default.aspx?id=" + groupId);
            }
            else
            {
                RaiseError(e.Exception, WebConsts.ERROR_MESSAGE_DEFAULT);
            }
        }

        private void SendMail()
        {
            MailOperations.SendSystemMail("Events", "EventCreated", User.Identity.Name, mailReplacement);
        }

        void CreatorSignUp(Guid eventId)
        {
            CheckBox ch = (CheckBox)FormView1.FindControl("chkCreatorSignUp");
            if (ch.Checked)
            {
                EventOperations.AddParticipantToEvent(eventId, Profile.UserId, "系统自动", true);
            }
        }

        void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
        {
            throw new NotImplementedException();
        }

        void InitializeFormData()
        {
            if (q == "new")
            {
                Sc_Profile myProfile = ProfileOperations.GetProfile(Profile.UserId);
                TextBox contactPeron = (TextBox)FormView1.FindControl("ContactPersonTextBox");
                contactPeron.Text = myProfile.FullName;
                try
                {
                    Sc_Address myAddress = ProfileOperations.GetAddress(Profile.UserId);
                    TextBox contactPhone = (TextBox)FormView1.FindControl("ContactPhoneTextBox");
                    contactPhone.Text = myAddress.Phone;
                    
                }
                catch
                { }

                TextBox contactEmail = (TextBox)FormView1.FindControl("ContactEmailTextBox");
                contactEmail.Text = Me.LoweredEmail;
            }
        }
    }
}
